#!/usr/bin/env python3
"""
TIR (C++ Template Instantiation Revealer) Demonstration Script

This script demonstrates the capabilities of TIR on various C++ template examples.
"""

import os
import sys
from pathlib import Path

# Configure libclang BEFORE adding to path or importing anything
print("🔧 Configuring libclang...")
try:
    from clang.cindex import conf
    # Try to auto-detect libclang library
    lib_path = None
    
    # Check environment variable first
    env_path = os.environ.get('LIBCLANG_PATH')
    if env_path and os.path.exists(env_path):
        lib_path = env_path
    else:
        # Try common locations
        import subprocess
        try:
            result = subprocess.run(['ldconfig', '-p'], capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                for line in result.stdout.splitlines():
                    if 'libclang.so' in line:
                        parts = line.split(' => ')
                        if len(parts) > 1:
                            candidate = parts[1].strip()
                            if os.path.exists(candidate):
                                lib_path = candidate
                                break
        except:
            pass
        
        # Fallback to common paths
        if not lib_path:
            common_paths = [
                '/usr/lib/llvm/19/lib64/libclang.so.19.1',
                '/usr/lib/llvm/18/lib64/libclang.so.18.1',
                '/usr/lib/llvm/17/lib64/libclang.so.17.1',
                '/usr/lib/libclang.so',
                '/usr/lib64/libclang.so',
            ]
            for path in common_paths:
                if os.path.exists(path):
                    lib_path = path
                    break
    
    if lib_path:
        print(f"   Found libclang at: {lib_path}")
        conf.set_library_file(lib_path)
        
        # Test configuration
        from clang.cindex import Index
        Index.create()
        print("✅ libclang configured successfully")
    else:
        print("❌ Could not find libclang library")
        print("   Please install clang or set LIBCLANG_PATH environment variable")
        sys.exit(1)
        
except Exception as e:
    print(f"❌ libclang configuration failed: {e}")
    print("   Please check your clang installation")
    sys.exit(1)

# Add tir to Python path after libclang configuration
sys.path.insert(0, str(Path(__file__).parent))

from tir.cli import TIRAnalyzer


def demo_header(title: str):
    """Print a demo section header."""
    print("\n" + "=" * 70)
    print(f"🎯 {title}")
    print("=" * 70)


def demo_simple_templates():
    """Demonstrate TIR on simple template examples."""
    demo_header("Simple Template Analysis")
    
    test_file = Path(__file__).parent / 'tests' / 'test_samples' / 'simple_templates.cpp'
    
    if not test_file.exists():
        print("❌ Demo file not found. Please ensure test samples are available.")
        return
    
    analyzer = TIRAnalyzer()
    
    examples = [
        (12, 20, "Basic std::vector<int>"),
        (15, 20, "Nested std::vector<std::vector<double>>"),
        (18, 20, "std::map<std::string, int>"),
        (21, 20, "Complex nested map"),
        (24, 15, "Auto variable with template deduction"),
    ]
    
    for line, col, description in examples:
        print(f"\n📍 {description} (Line {line}, Column {col})")
        print("-" * 50)
        
        try:
            result = analyzer.analyze_symbol_at_position(str(test_file), line, col, "basic")
            print(result)
        except Exception as e:
            print(f"❌ Error: {e}")


def demo_complex_templates():
    """Demonstrate TIR on complex template examples."""
    demo_header("Complex Template Analysis")
    
    test_file = Path(__file__).parent / 'tests' / 'test_samples' / 'complex_templates.cpp'
    
    if not test_file.exists():
        print("❌ Demo file not found. Please ensure test samples are available.")
        return
    
    analyzer = TIRAnalyzer()
    
    examples = [
        (34, 20, "Deeply nested templates"),
        (37, 20, "Custom template with namespace"),
        (40, 20, "Template alias usage"),
        (52, 20, "Ultra-complex map with all template parameters"),
    ]
    
    for line, col, description in examples:
        print(f"\n📍 {description} (Line {line}, Column {col})")
        print("-" * 50)
        
        try:
            result = analyzer.analyze_symbol_at_position(str(test_file), line, col, "detailed")
            print(result)
        except Exception as e:
            print(f"❌ Error: {e}")


def demo_vllm_style():
    """Demonstrate TIR on vLLM-style complex templates."""
    demo_header("vLLM-Style Complex Template Analysis")
    
    test_file = Path(__file__).parent / 'tests' / 'test_samples' / 'vllm_style.cpp'
    
    if not test_file.exists():
        print("❌ Demo file not found. Please ensure test samples are available.")
        return
    
    analyzer = TIRAnalyzer()
    
    examples = [
        (65, 50, "vLLM AttentionConfig instantiation"),
        (70, 50, "Complex AttentionKernel with multiple template parameters"),
        (95, 30, "Ultra-nested attention layers (real-world complexity)"),
        (116, 10, "Model state with extreme template nesting"),
    ]
    
    for line, col, description in examples:
        print(f"\n📍 {description} (Line {line}, Column {col})")
        print("-" * 50)
        
        try:
            result = analyzer.analyze_symbol_at_position(str(test_file), line, col, "detailed")
            print(result)
        except Exception as e:
            print(f"❌ Error: {e}")


def demo_json_output():
    """Demonstrate JSON output format."""
    demo_header("JSON Output Format (for programmatic use)")
    
    test_file = Path(__file__).parent / 'tests' / 'test_samples' / 'simple_templates.cpp'
    
    if not test_file.exists():
        print("❌ Demo file not found.")
        return
    
    analyzer = TIRAnalyzer()
    
    print("📍 Analyzing std::vector<int> with JSON output:")
    print("-" * 50)
    
    try:
        result = analyzer.analyze_symbol_at_position(str(test_file), 12, 20, "json")
        print(result)
    except Exception as e:
        print(f"❌ Error: {e}")


def demo_symbol_by_name():
    """Demonstrate symbol analysis by name."""
    demo_header("Symbol Analysis by Name")
    
    test_file = Path(__file__).parent / 'tests' / 'test_samples' / 'simple_templates.cpp'
    
    if not test_file.exists():
        print("❌ Demo file not found.")
        return
    
    analyzer = TIRAnalyzer()
    
    symbols = ["int_vector", "matrix", "string_to_int", "complex_map"]
    
    for symbol in symbols:
        print(f"\n📍 Analyzing symbol '{symbol}' by name:")
        print("-" * 50)
        
        try:
            result = analyzer.analyze_symbol_by_name(str(test_file), symbol, "basic")
            print(result)
        except Exception as e:
            print(f"❌ Error: {e}")


def demo_cli_usage():
    """Show CLI usage examples."""
    demo_header("CLI Usage Examples")
    
    print("TIR can be used from the command line in several ways:\n")
    
    examples = [
        ("Basic analysis by position:", 
         "python -m tir.cli -f ./tests/test_samples/simple_templates.cpp -l 12 -c 20"),
        
        ("Analysis by symbol name:",
         "python -m tir.cli -f ./tests/test_samples/simple_templates.cpp -s int_vector"),
        
        ("Detailed output format:",
         "python -m tir.cli -f ./tests/test_samples/simple_templates.cpp -l 12 -c 20 --format detailed"),
        
        ("JSON output for scripts:",
         "python -m tir.cli -f ./tests/test_samples/simple_templates.cpp -l 12 -c 20 --format json"),
        
        ("With project compile commands:",
         "python -m tir.cli -f ./src/main.cpp -l 42 -c 10 --compile-commands ./build/compile_commands.json"),
        
        ("Verbose output:",
         "python -m tir.cli -f ./tests/test_samples/simple_templates.cpp -l 12 -c 20 -v"),
    ]
    
    for description, command in examples:
        print(f"📝 {description}")
        print(f"   {command}")
        print()


def main():
    """Run the complete TIR demonstration."""
    print("🚀 TIR (C++ Template Instantiation Revealer) Demo")
    print("This demonstration shows TIR's capabilities on various C++ template examples.")
    print(f"📁 Working directory: {Path.cwd()}")
    
    try:
        # Check if we can import TIR components
        from tir import ASTParser, TypeResolver, OutputFormatter
        print("✅ TIR components loaded successfully")
    except ImportError as e:
        print(f"❌ Failed to load TIR components: {e}")
        print("💡 Make sure libclang is installed: pip install libclang")
        return
    
    # Run demonstrations
    demo_simple_templates()
    demo_complex_templates()
    demo_vllm_style()
    demo_json_output()
    demo_symbol_by_name()
    demo_cli_usage()
    
    print("\n" + "=" * 70)
    print("🎉 TIR Demonstration Complete!")
    print("=" * 70)
    print("\n💡 Next Steps:")
    print("   1. Try TIR on your own C++ files")
    print("   2. Use --compile-commands for project analysis")
    print("   3. Integrate with your IDE/editor workflow")
    print("   4. Consider migrating to C++ LibTooling for performance")
    print("\n🔗 For more information, see README.md")


if __name__ == '__main__':
    main()